package com.atguigu.serurity.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
	/**
	 * LoginUser这个类中的getPassword() getUsername() 都是继承自UserDetails
	 * 且返回值是User的账号和密码
	 */
	private User user;
	//权限信息成员变量
	private List<String> permissions;

	//redis默认不会把这个变量序列化，需要开启注解
	@JSONField(serialize = false)
	private List<SimpleGrantedAuthority> Authorities;

	public LoginUser(User user) {
		this.user = user;
	}

	public LoginUser(User user, List<String> permissions) {
		this.user = user;
		this.permissions = permissions;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {

		if (Authorities!=null){
			return Authorities;
		}
		/* //将权限信息封装到Authorities中
		List<GrantedAuthority> authorityList=new ArrayList<>();
		for (String permission : permissions) {
			//构造函数中的参数是权限信息->role
			SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(permission);
			authorityList.add(simpleGrantedAuthority);
;		}*/
		/*Authorities = permissions.stream().map(item -> {
			SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item);
			Authorities.add(simpleGrantedAuthority);
			return simpleGrantedAuthority;
		}).collect(Collectors.toList());*/

		 Authorities = permissions.stream()
				 .map(SimpleGrantedAuthority::new)
				 .collect(Collectors.toList());


		return Authorities;
	}

	@Override
	public String getPassword() {
		return user.getPassword();

	}

	@Override
	public String getUsername() {
		return user.getUsername();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
